package businesslogic;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.SQLException;
import java.util.ArrayList;

import database.UserService;

import po.CustomerPO;
import po.PromotionPO;
import po.StrategyPO;
import po.UserPO;
import startup.IOHelper;

import businesslogicservice.PromotionBLService;

public class PromotionBL extends UnicastRemoteObject implements PromotionBLService{
	
	UserService userDatabase;
	
	private String strategyFilename = "strategy.ser";
	
	public PromotionBL(String username, String password) throws RemoteException {
		try {
			userDatabase = new UserService(username, password);
		} catch (Exception e) {
			
		}
	}

	public void initStrategy() {
		StrategyPO strategy = new StrategyPO(1, 100, 1, 0.8);
		IOHelper.writeFile(strategyFilename, strategy);
	}
	
	public StrategyPO getStrategy() throws RemoteException {
		StrategyPO strategy = (StrategyPO) IOHelper.readFile(strategyFilename);
		return strategy;
	}

	public void modifyStrategy(StrategyPO strategy) throws RemoteException {
		IOHelper.writeFile(strategyFilename, strategy);
	}

	public void promote(PromotionPO promotion) throws RemoteException, SQLException{
		ArrayList<Integer> quota = promotion.getQuota();
		ArrayList<Integer> offsetTicketNumber = promotion.getOffsetTicketNumber();
		ArrayList<Integer> discountTicketNumber = promotion.getDiscountTicketNumber();
		
		for(int i=0; i<quota.size()-1; i++){
			ArrayList<UserPO> userList = userDatabase.findUser(quota.get(i), quota.get(i+1));
			
			for(int j=0; j<userList.size(); j++){
				
				UserPO user = userList.get(j);		
				CustomerPO customer = user.getCustomerPO();
				
				customer.setOffsetTicket( customer.getOffsetTicket() + offsetTicketNumber.get(i));
				customer.setDiscountTicket( customer.getDiscountTicket() + discountTicketNumber.get(i));
				
				user.setCustomerPO(customer);
				userDatabase.updateUser(user);
				
			}
		}
		
		int lastIndex = quota.size()-1;
		ArrayList<UserPO> userList = userDatabase.findUser( quota.get(lastIndex) );
		
		for(int j=0; j<userList.size(); j++){
			
			UserPO user = userList.get(j);		
			CustomerPO customer = user.getCustomerPO();
			
			customer.setOffsetTicket( customer.getOffsetTicket() + offsetTicketNumber.get(lastIndex));
			customer.setDiscountTicket( customer.getDiscountTicket() + discountTicketNumber.get(lastIndex));
			
			user.setCustomerPO(customer);
			userDatabase.updateUser(user);
			
		}
	}

}
